import axios from 'axios'
import {
	newWorkTextConfig,
	SUCCESS_REQUEST_STATUS
} from './config.js'
// axios网络请求
function ajax (Vue) {
  Vue.prototype.$baseURL = newWorkTextConfig.b_server_url
  /**
   * @param {Object | String} params  请求参数
   * @param {string} method 请求类型
   */
  Vue.prototype.$ajax = function (params, method = 'get') {
    const data = params['data'] || {}
    if (params['loading']) this.isLoading = true
    let [getData, postData, headers] = [null, null, null]
    if (method === 'post' || method === 'put' || params.special) {
			postData = params.special ? data : JSON.stringify(data),
			console.log(postData)
     // postData = JSON.stringify(data)
      headers = {
        'Content-Type': 'application/json'
      }
    } else {
      getData = data
	}
	return new Promise((reslove, reject) => {
		axios({
			method: method,
			url: `${this.$baseURL}${params['url']}`,
			params: getData,
			data: postData,
			headers: headers,
			withCredentials: true
			}).then(res => {
				console.log(res)
				if(res.status === 200 && res.data.status === 0) {
					reslove({
						data: res.data.data,
						status: 200
					})
				} else {
					reject({
						msg: res.data.message,
						status: 400,
					})
				}
			}).catch(err => {
				console.log(err)
				reject({
					msg: '服务器错误',
					status: 501,
				})
			})
	})
  }
 
  // get请求
  Vue.prototype.$get = function (params) {
	this.$ajax(params, 'get').then(res => {
		params.callback(res)
	}).catch(err => {
		params.callback(err)
	})
	
  }
 
  // post请求
  Vue.prototype.$post = function (params) {
    this.$ajax(params, 'post').then(res => {
    	params.callback(res)
    }).catch(err => {
    	params.callback(err)
    })
  }
 
  // put请求
  Vue.prototype.$put = function (params) {
    this.$ajax(params, 'put').then(res => {
    	params.callback(res)
    }).catch(err => {
    	params.callback(err)
    })
  }
 
  // patch请求
  Vue.prototype.$patch = function (params) {
    
  }
 
  // delete请求
  Vue.prototype.$delete = function (params) {
    this.$ajax(params, 'delete').then(res => {
    	params.callback(res)
    }).catch(err => {
    	params.callback(err)
    })
  }
}
 
if (typeof window !== 'undefined' && window.Vue) {
  window.Vue.use(ajax)
}
 
export default ajax
